import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store";
Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  routes,
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    };
  },
});

const whiteArr = ["Home", "Login", "Register", "Search", "Detail"];
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 开启进度条
  NProgress.start();
  const token = localStorage.token;

  if (token) {

    //判断我们去的是不是登录页,如果是,则直接导航到首页
    if (to.name === "Login") {

      next("/home");
    } else {
      // 判断用户名是否存在
      const isHaseNickName = !!store.state.User.userMessage.nickName;
      if (isHaseNickName) {

        // 如果存在,说明用户刚刚鉴权过,不需要再鉴权(因为只要页面一刷新或者重新打开,则用户名就会消失)然后直接放行
        next();
      } else {

        //要异常捕获,一旦请求用户信息失败,则说明当前的token是失效的或者是过期的
        try {

          //如果不存在,拿到token去请求用户信息
          await store.dispatch("User/getuserMessage");
          //加入请求成功,则直接放行
          next();
        } catch (e) {

          //说明token异常,此时就要直接跳转到登录页(并且一定要删除token)
          store.commit("User/remove_token");
          next("/login");
        }
      }
    }
  } else {
    console.log(whiteArr.includes(to.name));
    // console.log(7);
    if (whiteArr.includes(to.name)) {
      // console.log(8);
      next();
    } else {
      // console.log(9);
      next("/login");
    }
  }
  // next();
});
router.afterEach(() => {
  NProgress.done();
});
export default router;